<template>
  <div class="bg-white m-4 mr-0">
    <BasicTree
      title="分类列表"
      :treeData="treeData"
      :right-menu-list="[
        {
          // 文本
          label: '修改',
          // 是否禁用
          disabled: false,
          // 事件
          handler: (...record) => {
            handleCreate(record);
          },
          // 是否显示分隔线
          divider: true,
        },
      ]"
      :replaceFields="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    >
      <template #title="record">
        <div class="w-full flex justify-between">
          <div> {{ record.name }}</div>
          <div>
            <a-space>
              <a @click.stop="handleCreate(true, record)">编辑</a>
            </a-space>
          </div>
        </div>
      </template>

      <template #headerTitle>
        <BasicTitle class="w-1/2 flex justify-between">
          分类列表
          <a-button size="small" color="primary" @click="handleCreate">新增</a-button>
        </BasicTitle>
      </template>
    </BasicTree>
    <feed-type-drawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { BasicTitle } from '/@/components/Basic';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getListFeedTypeTree } from '/@/api/cuisine/feed';
  import AButton from '/@/components/Button/src/BasicButton.vue';
  import FeedTypeDrawer from './FeedTypeDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';

  export default defineComponent({
    name: 'FeedTypeTree',
    components: { AButton, BasicTree, BasicTitle, FeedTypeDrawer },

    emits: ['select'],
    setup(_, { emit }) {
      onMounted(() => {
        fetch();
      });

      const treeData = ref<TreeItem[]>([]);

      async function fetch() {
        treeData.value = (await getListFeedTypeTree({ type: 1 })) as unknown as TreeItem[];
      }

      function handleSelect(keys: string, e) {
        emit('select', keys[0]);
        console.log(keys, e);
      }

      const [registerDrawer, { openDrawer }] = useDrawer();

      function handleCreate(isUpdate = false, record) {
        openDrawer(true, {
          isUpdate: isUpdate,
          record,
        });
      }

      function handleSuccess() {
        fetch();
      }

      return { treeData, handleSelect, registerDrawer, handleCreate, handleSuccess };
    },
  });
</script>
